package com.hqd.ch03.v28.tx.transaction.interceptor;

import com.hqd.ch03.v28.aop.support.AopUtils;
import com.hqd.ch03.v28.aopalliance.intercept.MethodInterceptor;
import com.hqd.ch03.v28.aopalliance.intercept.MethodInvocation;
import lombok.Data;

import javax.sql.DataSource;

@Data
public class TransactionInterceptor extends TransactionAspectSupport implements MethodInterceptor {
    public static final int SYNCHRONIZATION_ALWAYS = 0;
    public static final int SYNCHRONIZATION_ON_ACTUAL_TRANSACTION = 1;
    public static final int SYNCHRONIZATION_NEVER = 2;
    private int transactionSynchronization = SYNCHRONIZATION_ALWAYS;
    private DataSource dataSource;
    private TransactionAttributeSource transactionAttributeSource;

    public TransactionInterceptor() {

    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Class<?> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);

        return invokeWithinTransaction(invocation.getMethod(), targetClass, new CoroutinesInvocationCallback() {
            @Override
            public Object proceedWithInvocation() throws Throwable {
                return invocation.proceed();
            }

            @Override
            public Object getTarget() {
                return invocation.getThis();
            }

            @Override
            public Object[] getArguments() {
                return invocation.getArguments();
            }
        });
    }
}
